/*
 * Copyright 2009 eBusinessInformation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.ymca.service.remotefile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import roboguice.inject.InjectResource;
import android.util.Log;

import com.excilys.ymca.R;
import com.excilys.ymca.model.Contact;
import com.excilys.ymca.model.RemoteFileContact;
import com.excilys.ymca.service.ContactService;
import com.excilys.ymca.service.exception.ServiceException;

/**
 * Implémentation de IContactListService qui va chercher la liste des contacts
 * sur un serveur distant.
 * 
 * @author Pierre-Yves Ricau ( py.ricau+ymca @ gmail.com )
 * 
 */
public class RemoteFileContactService implements ContactService {

	/**
	 * Marqueur pour les logs.
	 */
	private static final String	TAG	= RemoteFileContactService.class.getSimpleName();

	/**
	 * Serveur distant mettant à disposition la liste de contacts.
	 */
	@InjectResource(R.string.remote_file_host)
	private String				host;

	@Override
	public List<Contact> getContactList() throws ServiceException {

		ArrayList<Contact> contacts = new ArrayList<Contact>();

		try {
			URL url = new URL(host + "/contacts.txt");

			InputStream is = url.openStream();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(is));

				String line;
				while ((line = br.readLine()) != null) {
					StringTokenizer stk = new StringTokenizer(line, "|");
					contacts.add(new RemoteFileContact(stk.nextToken(), stk.nextToken(), stk.nextToken(), stk.nextToken()));
				}
			} finally {
				if (is != null) {
					is.close();
				}
			}
		} catch (IOException e) {
			/*
			 * Notez l'utilisation d'une classe de Log spécifique à Android.
			 * C'est le seul morceau de cette classe qui est lié à Android.
			 */
			Log.e(TAG, "Could not read contacts from the URL", e);
			throw new ServiceException(R.string.exception_contact_service_remote_file);
		}

		return contacts;
	}

}
